import { defineStore } from "pinia";
import { getMyCourseRecordAPI } from "@/apis/user";
import { DISPLAY_STATUS, DISPLAY_STATUS_TO_BACKEND } from "@/utils/constant";
import { cancelCourseAPI } from "@/apis/reservation";

export const useReservationStore = defineStore("reservation", {
  state: () => ({
    type: "",
    courseList: [],
    activeTab: "upcoming",
    selectedYear: new Date().getFullYear(),
    loading: false,
    showCancelCourseModel: false,
    currentCourse: null,
    // 状态选项卡
    statusTabs: [
      { id: DISPLAY_STATUS.UPCOMING, name: "待上课" },
      { id: DISPLAY_STATUS.COMPLETED, name: "已完成" },
      { id: DISPLAY_STATUS.CANCELLED, name: "已旷课" },
    ],
  }),
  getters: {
    convertedStatus: (state) => {
      return (
        DISPLAY_STATUS_TO_BACKEND[state.activeTab] ||
        DISPLAY_STATUS_TO_BACKEND[DISPLAY_STATUS.UPCOMING]
      );
    },
  },
  actions: {
    setReservationType(type) {
      this.type = type;
    },
    setActiveTab(tab) {
      this.activeTab = tab;
    },

    setSelectedYear(year) {
      this.selectedYear = year;
    },

    setCurrentCourse(course) {
      this.currentCourse = course;
    },

    setShowCancelCourseModel(show) {
      this.showCancelCourseModel = show;
    },

    // 取消课程
    async cancelCourseHandle(reason) {
      if (!this.currentCourse) {
        uni.showToast({
          title: "请选择课程",
          icon: "none",
        });
        return;
      }
      const res = await cancelCourseAPI({
        courseCode: this.currentCourse.courseCode,
        reason: reason || "用户取消",
      });
      if (res.code === "200") {
        this.fetchCourseList();
        this.setShowCancelCourseModel(false);
      }
    },

    // 获取课程列表
    async fetchCourseList() {
      try {
        this.loading = true;
        const params = {
          year: this.selectedYear,
          statusList: this.convertedStatus,
        };

        const res = await getMyCourseRecordAPI(params);
        if (res.code === "200") {
          this.courseList = res.data.list || [];
          return true;
        } else {
          uni.showToast({
            title: res.msg || "获取课程列表失败",
            icon: "none",
          });
          return false;
        }
      } catch (error) {
        console.error("获取课程列表错误:", error);
        uni.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
        });
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 处理选项卡切换
    async handleTabChange(tab) {
      this.activeTab = tab;
      return await this.fetchCourseList();
    },

    // 处理年份切换
    async handleYearChange(year) {
      this.selectedYear = year;
      return await this.fetchCourseList();
    },
  },
});
